package Auxiliary;

import com.sun.org.apache.bcel.internal.generic.NEW;

import java.util.concurrent.*;

/**
 * @Author ufo
 * @Description TODO
 * @Date 2021/1/20 16:31
 * @Version 1.0
 */
public class Auxiliary {

    public static void semaphoreTest(String[] args) {
        Semaphore semaphore=new Semaphore(4);
        for (int i = 0; i < 8; i++) {
            new Thread(()->{
                try {
                    //抢占
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢到了");
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println(Thread.currentThread().getName()+"离开了");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                finally {
                    //释放
                    semaphore.release();
                }
            }).start();

        }
    }



    public static void cyclicBarrierTest(String[] args) throws InterruptedException, BrokenBarrierException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
            System.out.println("召唤神龙成功");
        });
        for (int i = 0; i < 100; i++) {
            final int tmp=i;
            new Thread(() -> {
                System.out.println(tmp);
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }

            }, String.valueOf(i)
            ).start();
        }

    }


    public static void countDownLatchTest(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                countDownLatch.countDown();
                System.out.println("=====出门=====");
            }, String.valueOf(i)
            ).start();
        }
        countDownLatch.await();
        System.out.println("===关门====");
    }





}
